<?php
class LoginController extends Zend_Controller_Action
{
	public function init()
	{
		$this->_helper->layout()->setLayout('admin');
		
	}
	
	public function loginAction()
	{
		$loginForm = new Inc_Form_Login();
		$this->view->loginForm = $loginForm;
		
		if ($this->getRequest()->isPost())
		{
			if($loginForm->isValid($this->getRequest()->getPost()))
			{
				$values = $loginForm->getValues();
			
				$adapter = new Zend_Auth_Adapter_Doctrine($values['username'], $values['password']);
			
				
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($adapter);	
				
				
				if ($result->isValid())
				{
					$session = new Zend_Session_Namespace('zend.auth');
					$session->user = $adapter->getResultArray('Password');
					
					
					if (isset($session->requestURL))
					{
						$url = $session->requestURL;
						unset($session->requestURL);
						
						$this->_redirect($url);
					}
					else 
					{
						$this->_helper->getHelper('FlashMessenger')->addMessage('You loggin successfule');
						$this->_redirect('/admin/login/success');
					}
				}
				else 
				{
					$this->view->message = 'login error, please try again';
				}
			
			}
		}
	}
	
	public function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		Zend_Session::destroy();
		$this->_redirect('/admin/login');
	}
	
	public function successAction()
	{
		if($this->_helper->getHelper('FlashMessenger')->getMessages())
		{
			$this->view->message = $this->_helper->getHelper('FlashMessenger')->getMessages();
		}
		else 
		{
			$this->_redirect('/');
		}
	}
}